<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectTicketDangerModel;
use app\app\model\ProjectModel;
use app\app\model\ProjectTicketModel;
use app\BaseController;
use app\Request;
use think\exception\ValidateException;
use think\facade\Filesystem;


class ProjectTicket extends BaseController
{
    public function list()
    {
        $data = $this->request->param();
        $page_size = input('pageSize', '20');
        $where = "1=1";
        if (!empty($data['oper_time'])) {
            $where .= "  AND a.oper_time = " . $data['oper_time'];
        }
        if (!empty($data['ticket_name'])) {
            $where .= " AND a.ticket_name = " . $data['ticket_name'];
        }
//        if (isset($data['user_name']) && !empty($data['user_name'])) {
//            $where .= " AND b.link_user_id like '%" . $data['user_name'] . "%'";
//        }

        $list = ProjectTicketModel::alias('a')->field('a.*, c.file_name, b.project_name')
            ->leftjoin('t_project b', 'b.id = a.project_id')
            ->leftjoin('sys_file_info c', 'c.file_id = a.file_id')
            ->paginate([
                'list_rows' => $page_size,
                'var_page' => 'pageNum',
            ]);
        $this->success('success', $list);
    }

    public function add(Request $request)
    {
        $data = $request->param();
        $model = new ProjectTicketModel();
        $data['oper_time'] = date('Y-m-d H:i:s', time());
        $result = $model->save($data);
        if ($result !== false) {
            $this->success('添加成功!');
        } else {
            $this->error("保存失败！");
        }
    }

    public function update(Request $request)
    {
        $data = $request->param();
        $id = $request->param('id', 0, 'intval');
        $result = ProjectTicketModel::strict(false)->where('id', $id)->update($data);
        if ($result !== false) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }


    public function delete(Request $request)
    {
        $data = $request->param();
        $ids = $data['ids'];
        ProjectTicketModel::destroy(function ($query) use ($ids) {
            $query->where('id', 'in', $ids);
        });
    }

    /**
     * 风险等级导入
     * @return string|void
     * @author Kongkai
     * @date 2022-03-11
     */
    public function importData()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'risk', $file['file']);

        $data = (new FileImport())->ExcelImport($file_path . $file_name);

        $insert_array = [];
        foreach ($data as $k => $v) {
            if ($k == 0) continue;

            $project = ProjectModel::where('project_name', $v[0])->find();
            if (empty($project)) continue;

            $project_id = $project->id;

            $insert_array[] = [
                'project_id' => $project_id,
                'construction_name' => $v[1] ?: null,
                'ticket_level' => $v[2] ?: null,
                'danger_level' => $v[3] ?: null,
                'ticket_position' => $v[4] ?: null,
                'ticket_name' => $v[5] ?: null,
                'ticket_quantity' => $v[6] ?: null,
                'ticket_content' => $v[7] ?: null,
                'begin_time' => $v[8] ?: null,
                'end_time' => $v[9] ?: null,
                'real_quantity' => $v[10] ?: null,
                'ticket_man' => $v[11] ?: null,
                'ticket_state' => $v[12] ?: null,
                'technical_plan_name' => $v[13] ?: null,
                'oper_time' => date('Y-m-d H:i:s'),
            ];
        }

        try {
            (new ProjectTicketModel())->insertAll($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }
}
